<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { Product } from '@/types/product'
import { productService } from '@/services/apiService'
import { ElCard, ElButton, ElImage, ElRow, ElCol, ElMessage } from 'element-plus'
import LoadingSpinner from '@/components/LoadingSpinner.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const productId = Number(route.params.id)
const product = ref<Product | null>(null)
const loading = ref(false)
const activeImageIndex = ref(0) // 当前选中的图片索引

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true
  try {
    const data = await productService.getProductDetail(productId)
    product.value = data
    console.log('Fetched product detail:', product.value)
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 切换显示的图片
const switchImage = (index: number) => {
  activeImageIndex.value = index
}

// 与卖家聊天
const chatWithSeller = async () => {
  if (!userStore.isLogin) {
    // 未登录，跳转到登录页面
    router.push('/login')
    return
  }

  if (product.value) {
    // 检查卖家是否是当前用户自己
    if (product.value.uid === userStore.userInfo.id) {
      ElMessage.warning('不能与自己聊天')
      return
    }
    
    try {
      localStorage.setItem('chatTargetUser', JSON.stringify({
        receiverId: product.value.uid,
        username: product.value.seller_username
      }))
      router.push('/chat')
    } catch (error) {
      console.error('获取会话ID失败:', error)
      ElMessage.error('无法启动聊天，请稍后重试')
    }
  }
}

// 返回首页
const goBack = () => {
  router.back()
}

// 页面初始化
onMounted(() => {
  if (!productId) {
    router.push('/')
    return
  }
  fetchProductDetail()
})
</script>

<template>
  <div class="product-detail-container">
    <div class="breadcrumb">
      <a href="#/" @click.prevent="goBack">首页</a> > <span>{{ product?.title }}</span>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <LoadingSpinner fullScreen />
    </div>

    <!-- 内容区域 -->
    <div v-else-if="product">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="product-images">
            <el-row :gutter="20">
              <!-- 左侧缩略图列表 -->
              <el-col :span="6" class="thumbnail-list">
                <div 
                  v-for="(image, index) in product.images" 
                  :key="index" 
                  :class="['thumbnail-item', { 'active': index === activeImageIndex }]"
                  @click="switchImage(index)"
                >
                  <el-image
                    :src="'http://localhost:8000/media/' + image"
                    alt="商品缩略图"
                    fit="cover"
                    class="thumbnail-image"
                  />
                </div>
              </el-col>
              
              <!-- 右侧主图显示区 -->
              <el-col :span="18" class="main-image-container">
                <el-image
                  v-if="product.images.length > 0"
                  :src="'http://localhost:8000/media/' + product.images[activeImageIndex]"
                  alt="商品主图"
                  fit="contain"
                  class="main-image"
                />
                <div v-else class="no-image">暂无图片</div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="product-info">
            <h1>{{ product.title }}</h1>
            <p class="price">¥{{ product.price }}</p>
            <p class="view-count">浏览量: {{ product.view_count }}</p>
            <p class="description">{{ product.description }}</p>

            <div class="seller-info">
              <h3>卖家信息</h3>
              <p><strong>姓名：</strong>{{ product.seller_username }}</p>
            </div>

            <div class="seller-actions">
              <el-button type="success" @click="chatWithSeller">与卖家聊天</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 无数据状态 -->
    <div v-else class="no-data">
      <p>商品不存在或已下架</p>
      <el-button @click="goBack">返回首页</el-button>
    </div>
  </div>
</template>

<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  color: #6c757d;
  margin-bottom: 20px;
  font-size: 0.9em;
}

.product-images {
  height: 600px; /* 固定图片区域高度 */
}

.thumbnail-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  height: 100%;
  max-height: 600px;
  overflow-y: auto;
}

.thumbnail-item {
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: border-color 0.3s;
  flex-shrink: 0; /* 防止缩略图被压缩 */
}

.thumbnail-item:hover {
  border-color: #409eff;
}

.thumbnail-item.active {
  border-color: #409eff;
}

.thumbnail-image {
  width: 100%;
  height: 100px; /* 统一缩略图高度 */
  border-radius: 6px;
  object-fit: cover; /* 统一图片填充方式 */
}

.main-image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 600px; /* 固定主图容器高度 */
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: hidden; /* 防止图片超出容器 */
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 统一主图填充方式，保持宽高比 */
}

.no-image {
  color: #999;
  font-size: 16px;
}

.product-info {
  height: 600px; /* 固定商品信息区域高度 */
  display: flex;
  flex-direction: column;
}

.product-info h1 {
  margin-top: 0;
  color: #333;
  flex-shrink: 0;
}

.price {
  font-size: 1.5em;
  color: #d9534f;
  font-weight: bold;
  margin: 10px 0;
  flex-shrink: 0;
}

.view-count {
  font-size: 0.9em;
  color: #666;
  margin: 5px 0;
  flex-shrink: 0;
}

.description {
  line-height: 1.6;
  color: #555;
  margin: 20px 0;
  flex-grow: 1;
  overflow-y: auto; /* 如果描述过长，允许滚动 */
}

.seller-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin: 20px 0;
  flex-shrink: 0;
}

.seller-info h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.seller-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  flex-shrink: 0;
}

.no-data {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}
</style>